<?php
declare (strict_types=1);

namespace app\admin\logic\material;

use app\admin\logic\system\Log;
use app\admin\model\material\Category as CategoryModel;
use app\common\exception\LogicException;

/**
 * 素材分组管理
 */
class Category extends CategoryModel
{
    /**
     * 创建分组
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-21
     *
     * @param array $data [description]
     * @return   [type]                               [description]
     */
    public function createCategory(array $data)
    {
        $check                  = $data;
        $check['material_type'] = $this->materialTypes[$data['material_type']] ?? 0;
        // 验证数据
        $this->getValidate()->scene('create')->failException()->check($check);
        // 用户信息
        $res = $this->save($data);
        // 创建成功
        if (!$res) {
            throw new LogicException('创建分组失败');
        }

        Log::write('新建素材分组【' . $data['title'] . '】', 'material', 'create', true);

        // 返回值
        return $this;
    }

    /**
     * 编辑分组
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-23
     *
     * @param    [type]                         $id   [description]
     * @param    [type]                         $data [description]
     * @return   [type]                               [description]
     */
    public function updateCategory($id, $data)
    {
        $category = $this->where('id', $id)->findOrFail();

        $check       = $data;
        $check['id'] = $id;
        // 验证数据
        $this->getValidate()->scene('edit')->failException()->check($check);

        if (!$category->save($data)) {
            throw new LogicException('修改分组失败');
        }

        Log::write('更新素材分组【' . $category->title . '】', 'material', 'update', true);

        return $category;
    }

    /**
     * 删除素材分组
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-23
     *
     * @param    [type]                         $id [description]
     * @return   [type]                             [description]
     */
    public function deleteCategory($id)
    {
        $category = $this->where('id', $id)->findOrFail();
        // 移动到默认分组
        app(Material::class)->where('material_category_id', $id)->save(['material_category_id' => -1]);

        if (!$category->delete()) {
            throw new LogicException("删除失败");
        }

        Log::write('删除素材分组【' . $category->title . '】', 'material', 'delete', true);
    }

    /**
     * 获取列表
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-04-21
     *
     * @param string $type 类型
     * @return   [type]                               [description]
     */
    public function getList(string $type)
    {
        return $this->scope('materialType', $type)->select();
    }
}
